package com.yksj.healthtalk.ui.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.InfoAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.ShopEntityClassify;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 是医疗类的时候查询条件
 * @author Administrator
 *
 */
public class ServerCenterSeachDoctorActivity extends BaseFragmentActivity implements OnClickListener {

	private String id;//商户id
	private String type;//Salon-沙龙，Service-客服，Goods-商品
	 private  int mStackLevel = 1;
	 private ShopEntityClassify mShopEntityClassify  ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.server_center_docter);
		initTitle();
		initView();
		id = getIntent().getStringExtra("id");
		type = getIntent().getStringExtra("type");
		
		 if (savedInstanceState == null) {
	            // Do first time initialization -- add initial fragment.
	            Fragment newFragment = CountingFragment.newInstance(mStackLevel,mShopEntityClassify,type,id);
	            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
	            ft.add(R.id.simple_fragment, newFragment).commit();
	        } else {
	            mStackLevel = savedInstanceState.getInt("level");
	        }
	}
	
	private void initView() {
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText("分类查询");
		titleRightBtn2.setVisibility(View.GONE);
		titleRightBtn2.setText("确定");
		titleRightBtn2.setOnClickListener(this);
	}

	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("level", mStackLevel);
    }
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		if (arg1 == 0 && arg0 == 0&& arg2 != null) {
			if (arg2.hasExtra("classID")) {
				Intent intent=new Intent(this,ServerCenterDoctorListActivity.class);
				intent.putExtra("classID", arg2.getExtras().getString("classID"));
				startActivity(intent);
				overridePendingTransition(R.anim.anim_enter,R.anim.anim_exit);
			}
		}
		super.onActivityResult(arg0, arg1, arg2);
	}
	
	
	
	 public static class CountingFragment extends Fragment implements OnItemClickListener{
	        int mNum;
			private InfoAdapter adapter;
			private ShopEntityClassify classify;
			private ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
			private List<ShopEntityClassify> classifies;
			private String id;//商户id
			private String type;//Salon-沙龙，Service-客服，Goods-商品
			
	        static CountingFragment newInstance(int num,ShopEntityClassify classify,String type ,String id) {
	            CountingFragment f = new CountingFragment();

	            // Supply num input as an argument.
	            Bundle args = new Bundle();
	            args.putInt("num", num);
	            args.putString("type", type);
	            args.putString("id", id);
	            args.putSerializable("mShopEntityClassify", classify);
	            f.setArguments(args);
	            return f;
	        }

	        @Override
	        public void onCreate(Bundle savedInstanceState) {
	            super.onCreate(savedInstanceState);
	            mNum = getArguments() != null ? getArguments().getInt("num") : 1;
	            classify = (ShopEntityClassify) (getArguments().getSerializable("mShopEntityClassify") );
	            type = getArguments().getString("type");
	            id = getArguments().getString("id");
	            }

	        /**
	         * The Fragment's UI is just a simple text view showing its
	         * instance number.
	         */
	        @Override
	        public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                Bundle savedInstanceState) {
	            View v = inflater.inflate(R.layout.server_center_docter_list, container, false);
	            ListView mListView = (ListView)v.findViewById(R.id.listview);
	    		adapter = new InfoAdapter(getActivity(), data , true);
	    		mListView.setAdapter(adapter);
	    		adapter.setHasLevel(true);
	    		mListView.setOnItemClickListener(this);
	            if (mNum == 1) {
	            	data.clear();
		    		initData();
				}else {
					classifies = ShopEntityClassify.SearchDoctorsToList(classify.getSUBLIST());
		 			int size = classifies.size();
		 			String [] str = new String[size+1];
		 			str[0] = "全部";
		 			for (int i = 0; i < classifies.size(); i++) {
		 				str[i+1] = classifies.get(i).getCLASS_NAME();
		 				if (classifies.get(i).getSUBLIST().length() >3) {
		 					adapter.addSelect(i+1);
		 				}
		 			}
		 			data.clear();
		 			setData(str);
		 			adapter.notifyDataSetChanged();
				}
	            return v;
	        }

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				if (position !=0) {
					//判断是否是最后一页
					JSONArray array = null;
					try {
						array = new JSONArray(classifies.get(position-1).getSUBLIST());
					} catch (JSONException e) {
						e.printStackTrace();
					}
					if (array.length() == 0) {
						Intent intent = getActivity().getIntent();
						intent.putExtra("classID", classifies.get(position-1).getCLASS_ID());
						getActivity().setResult(RESULT_OK, intent);
						getActivity().finish();
						getActivity().overridePendingTransition(R.anim.back_enter,R.anim.back_exit);
					}else {
						((ServerCenterSeachDoctorActivity) getActivity()).addFragmentToStack(classifies.get(position-1));
					}
				}else {
					if (classify == null) {//第一个全部
						Intent intent = getActivity().getIntent();
						intent.putExtra("classID", "");
						getActivity().setResult(RESULT_OK, intent);
						getActivity().finish();
						getActivity().overridePendingTransition(R.anim.back_enter,R.anim.back_exit);
					}else {//其他全部
						Intent intent = getActivity().getIntent();
						intent.putExtra("classID", classify.getCLASS_ID());
						getActivity().setResult(RESULT_OK, intent);
						getActivity().finish();
						getActivity().overridePendingTransition(R.anim.back_enter,R.anim.back_exit);
					}
				}
			}
			
			  private void setData(String[] strs) {
					for (int i = 0; i < strs.length; i++) {
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("id", i);
						map.put("title", strs[i]);
						map.put("content", "");
						data.add(map);
					}
			  }
			  
				public  void initData() {
					
					HttpRestClient.doHttpServerSalonSeach(id,type,"10",new AsyncHttpResponseHandler(){

						private LodingFragmentDialog showLodingDialog;
						@Override
						public void onSuccess(int statusCode, String content) {
							super.onSuccess(statusCode, content);
							 classifies = ShopEntityClassify.SearchDoctorsToList(content);
							int size = classifies.size();
							String [] str = new String[size+1];
							str[0] = "全部";
							for (int i = 0; i < ShopEntityClassify.SearchDoctorsToList(content).size(); i++) {
								str[i+1] = classifies.get(i).getCLASS_NAME();
								if (classifies.get(i).getSUBLIST().length() >3) {
									adapter.addSelect(i+1);
								}
							}
							setData(str);
							adapter.notifyDataSetChanged();
						}
						
						@Override
						public void onStart() {
							super.onStart();
							showLodingDialog = LodingFragmentDialog.showLodingDialog(getChildFragmentManager(), "请稍后...");
						}
						@Override
						public void onFinish() {
							showLodingDialog.dismissAllowingStateLoss();
							super.onFinish();
						}
						
					});
					
				}
	    }
	 
		public void addFragmentToStack(ShopEntityClassify mShopEntityClassify) {
	        mStackLevel++;
	        // Instantiate a new fragment.
	        Fragment newFragment = CountingFragment.newInstance(mStackLevel,mShopEntityClassify,type,id);
	        // Add the fragment to the activity, pushing this transaction
	        // on to the back stack.
	        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
	        ft.replace(R.id.simple_fragment, newFragment);
	        ft.addToBackStack(null);
	        ft.commit();
	    }
		
	}
